import { login, logout, } from '@/api/login'
import { registerUser, loginUser } from '@/api/project/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { encryptData } from "@/utils/aes";

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    deptId: '',
    roles: [],
    permissions: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_DEPTID: (state, deptId) => {
      state.deptId = deptId
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      var param = {
        userName: userInfo.username.trim(),
        password: userInfo.password,
        enCode: userInfo.enCode,
        uuid: userInfo.uuid,
        code: userInfo.code,
      }
      const type = userInfo.type // 0注册  1登录
      return new Promise((resolve, reject) => {
        if (type === 0) {
          param.mobile = encryptData(userInfo.mobile)
          registerUser(param).then(res => {
            setToken(res.data)
            commit('SET_TOKEN', res.data)
            resolve()
          }).catch(error => {
            reject(error)
          })
        } else {
          loginUser(param).then(res => {
            setToken(res.data)
            commit('SET_TOKEN', res.data)
            resolve()
          }).catch(error => {
            reject(error)
          })
        }
      })
    },


    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
